/***
 * 编写人：田光辉
 * 日期：2013-09-03
 */
document.write("<script language='javascript' src='js/frame/validates.js'></script>");
document.write("<script language='javascript' src='js/frame/ajaxfileupload.js'></script>");

var loadingIndex;
function ajax(url,callback){
	$.ajax({
		type:"POST", 
		url:url,
		data:"",
		dataType:"json",
		error:function(){top.errMsg("操作失败，请重试！");}, 
		success:callback
	});
}

$(document).ready(function(){
	/*
	var intiMultiSelectVal = function(form){
		var multiselects = $(".multiselect");
		if(multiselects.length == 0){
			return false;
		}
		multiselects.each(function(){
			var name = $(this).attr("realName");
			var checks = $(this).multiselect("getChecked");
			var cids = new Array();
			if(null != checks && checks.length > 0){
				for(var i = 0; i<checks.length; i++){
					cids.push('<input type="hidden" name="'+name+'" value="'+checks[i].value+'"/>');
				}
			}
			var mdivs = form.find("#multiselectDiv-"+name);
			if(mdivs.length > 0){
				mdivs.empty().append(cids.join(""));
			}else{
				form.append('<div id="multiselectDiv-'+name+'" style="display:none;">'+cids.join("")+'</div>');
			}
		});
		
	};*/
	
	$(".btn_res").click(function(){
		$(this).parent()[0].reset();
	});
	
	var getFileIds = function(form){
		var fids = [];
	    form.find(":file").each(function(i,val){
	    	fids.push($(this).attr("id"));
	    });
		return fids;
	};
	
	var suc = function(data, status,form){
		if(data.result != undefined){
   		 if(data.result == true || data.result == "true"){
                	$("input[type=submit]").removeAttr('disabled');
                	if(data.message != undefined && data.message != null && data.message != "" ){
                 	     layer.msg(data.message,{time: 1000},function(){
	                 	    	if(undefined != data.view && "undefined" != data.view  && data.view !=null && data.view !=""){
	                        		if(data.top == true || data.top == "true"){
	                        			top.location.href = getRootPath() +"/" +data.view;
	                        		}else{
	                        			location.href = getRootPath() +"/" +data.view;
	                        		}
	                        	    return ;
	        	                }
	                        	if(data.func != undefined && "undefined" != data.func && data.func != null && data.func != ""){
	                        		eval(eval(data.func));
	                        	}
	                        	
	                        	
	                        	var parentReload = form.attr("parentReload");
	                        	if("true" == parentReload){
	                        		parent.location.reload();
	                        	}
	                        	
	                           //如果操作成功则在父页面做标记
	                           tagService();
	                         //表单提交之后下一步动作
	                           var nextStep = form.attr("nextStep");
	                           if(nextStep != undefined){
	                        	 //如果是close则关闭窗口
	        	                   if(nextStep == "close"){
	        	                	   tagService();
	        	                	   
	        	                	   var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
	        	                	   parent.layer.close(index);
	        	                   }
	        	                   //如果是reset则刷新窗口
	        	                   if(nextStep == "reset"){
	        	                	  self.location.reload(false);
	        	                   }
	                           }
                 	     });
                     }else{
                    	 layer.msg("保存成功!");
                     }
                	
                }else{
                	if(data.message != null || data.message != ""){
                		layer.msg(data.message);
                    }else{
                    	layer.msg("数据提交异常，请检查后重试");
                    }
                   $("input[type=submit]").removeAttr('disabled');
                }
		   	 }else{
		   		    data = eval("("+data+")");
		   		    
			   		 if(data.logout){
			  		   layer.alert("登陆失效，请重新登陆",{closeBtn:false},function(){
			  			   location.href = "login";
			  		   });
			  		   return false;
			  	    }
		   	 }
		
		layer.close(loadingIndex);
	};
	var init = function(){
		var forms = $("form.formEditor");
		   if(forms.length>0){
		      $.each(forms,function(i,val){
		    	  var form = $(val);
		        	 form.submit(function(){
				          var valiFlag = valiForm(form);
				          if(!valiFlag){
				        	  return false;
				          }
				          
				          var beforeSubmit = form.attr("beforeSubmit");
				          if(beforeSubmit){
				        	  var beforeSubmitFlag = eval(eval(beforeSubmit+'()'));
				        	  if(!beforeSubmitFlag){
				        		  return false;
				        	  }
				          }
				          
				          
				         //intiMultiSelectVal(form);
			             var url = $(this).attr("action");
			             var params = $(this).serializeArray();
			             //loadingIndex = layer.msg('正在提交数据..', {shade:0.00001,icon: 16,time: 1000*60*10 });
			             $.ajaxFileUpload
			     		 (
			     			{
			     				url:url,
			     				secureuri:false,
			     				fileElementId:getFileIds(form),
			     				dataType: 'json',
			     				data: params,
			     				success: function(data, status){
			     					suc(data, status,form);
			     				},
			     				error: function (data, status, e)
			     				{
			     					//layer.close(loadingIndex);
			     					//layer.msg("数据提交异常，请检查后重试");
			     					//alert(e);
			     				}
			     			}
			     		 );
			              
			             return false;
			         });
		      });
		   }
	}
	
	
	var loadForms = $(".loadForm");
	if(loadForms.length > 0){
		loadForms.load(loadForms.attr("data-url"),function(){
			init();
			if($(".editSelect").length > 0){
				$('.editSelect').editableSelect({filter:false});
			}
		});
	}else{
		init();
	}
   
});


//后台操作成功后标记父页面，判断窗口关闭时是否要刷新datalist列表
function tagService(){
	var pbody = $("body",window.top.document);
    if(pbody.find("#formtag").length>0){
 	   pbody.find("#formtag").text(1);
    }else{
 	   pbody.append('<span id="formtag" style="display: none;">1</span>');
    }
}
function clearNoNum(obj){
	obj.value = obj.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
	obj.value = obj.value.replace(/^\./g,""); //验证第一个字符是数字而不是
	obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的
	obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
	obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
}